#include <cstdlib>
#include <ctime>
#include <cstring>
#include <cerrno>
#include <unistd.h>
#include "socket.hpp"
#include "protocol.hpp"

// ./client 127.0.0.1 8080
int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        std::cout << "Usage: " << argv[0] << " ip port" << std::endl;
        return 1; 
    }
    uint16_t port = std::stoi(argv[2]);
    std::string ip = argv[1]; 
    
    Sock sockfd;
    sockfd.Socket();
    if(sockfd.Connect(port, ip) != 0)
    {
        perror("connect fail");
        return 1;
    }
    
    srand(time(nullptr) ^ getpid());
    int cnt = 10, i = 0;
    std::string opons = "+-*/";
    std::string in_buffer;
    while(i++ < cnt)
    {
        std::cout << "第 " << i << " 次测试！" << std::endl; 
        int x = rand() % 100 + 1;
        usleep(1234);
        char op = opons[rand() % static_cast<int>(opons.size())];
        usleep(4321);
        int y = rand() % 100 + 1;
        std::cout << "成功制作任务: " << x << op << y << std::endl;

        Request st(x, y, op);
        std::string package;
        st.Serialize(&package);
        package = Encode(package);
        std::cout << "发出的报文: \n" << package << std::endl;

        write(sockfd.getsockfd(), package.c_str(), package.size());
        

        char buffer[1024];
        ssize_t n = read(sockfd.getsockfd(), buffer, sizeof(buffer)-1);
        if(n > 0)
        {
            buffer[n] = '\0';
            in_buffer += buffer;
            std::string content;
            Decode(in_buffer, content);

            Response resp;
            resp.Deserialize(content);
            
            resp.DebugPrint();
        }
        sleep(1);
    }


    sockfd.Close();
    return 0;
}